<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use EasyWeChat\Factory;
use app\model\JdHistory;
use app\model\JdUser;
use app\model\JdBeanRecord;

class CheckDreamFactory extends Command
{
    protected $app;
    protected function configure()
    {
        // 指令配置
        $this->setName('app\command\checkdreamfactory')
            ->setDescription('the app\command\CheckDreamFactory command');
    }

    protected function execute(Input $input, Output $output)
    {
        $config = config('wechat');
        $this->app = Factory::officialAccount($config);

        $users = JdUser::select();

        foreach ($users as $key => $value) {
            if(!$value->cookie || $value->expired)
                continue;
            $this->getFreeFruit($value, $output);
        }
    }

    protected function getFreeFruit(JdUser $user, Output $output) {
        $headers = [
            'User-Agent: jdpingou;iPhone;3.14.4;14.0;ae75259f6ca8378672006fc41079cd8c90c53be8;network/wifi;model/iPhone10,2;appBuild/100351;ADID/00000000-0000-0000-0000-000000000000;supportApplePay/1;hasUPPay/0;pushNoticeIsOpen/1;hasOCPay/0;supportBestPay/0;session/62;pap/JA2015_311210;brand/apple;supportJDSHWK/1;Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148',
            'Accept: application/json,text/plain, */*',
            'Accept-Encoding: gzip, deflate, br',
            'Accept-Language: zh-cn',
            'Connection: keep-alive',
            'Host: m.jingxi.com',
            'Referer: https://wqsd.jd.com/pingou/dream_factory/index.html',
            'pragma: no-cache',
            "cache-control: no-cache",
            "sec-fetch-dest: empty",
            "sec-fetch-mode: cors",
            "sec-fetch-site: same-site",
        ];
        $response = '';
        try {
            $functionId = 'userinfo/GetUserInfo';
            $body="pin=&sharePin=&shareType=&materialTuanPin=&materialTuanId=";
            $t = time() * 1000;
            $response = $this->curl_get("https://m.jingxi.com/dreamfactory/${functionId}?zone=dream_factory&${body}&sceneval=2&g_login_type=1&_time=${t}&_=${t}",
                $user->cookie,
                $headers
            );
            // $output->writeln($response);
            // {"data":{"assistCondition":{"assistConditionMsg":"","assistNumCurrent":0,"assistNumLimit":0,"assistNumMax":0,"assistRemindKey":"","assistRemindUser":"","commodityAppLimitFlag":0,"factoryStatus":0,"hireNumLimit":0,"reAssistFlag":0,"sharePin":"","sharePinHeadImage":"//img12.360buyimg.com/img/s70x70_jfs/t1/90450/13/19517/14076/5e9ff3b4Ecdd7f382/76bfe250839dba31.jpg"},"assistMaterialTuanCondition":{"assistAppFlag":0,"assistSelfFlag":0,"commodityList":[],"limitTime":0,"materialName":"","materialPicture":"","materialStatus":0,"outOfStockFlag":0,"remindMsg":"","sharePin":"","sharePinNickname":"","startTime":0,"tuanId":""},"deviceList":[{"createTime":1604029564,"deviceDimId":1,"deviceId":16477065,"factoryId":16477064,"updateTime":1604029564}],"factoryList":[{"createTime":1604029564,"factoryId":16477064,"name":"陈乐182的梦工厂","updateTime":1604029564}],"moderWorkerInfo":{"yesterdayModerWorkerChampionInfo":{"encryptPin":"","headImage":"","nickName":""}},"newFactoryFlower":{"factoryFlowerSendFlag":0,"sendElectric":0},"productionList":[{"beginTime":1609248417,"commodityDimId":992,"createTime":1609248417,"dataMark":0,"deviceId":16477065,"endTime":1610565621,"exchangeStatus":3,"factoryId":16477064,"investedElectric":780000,"needElectric":780000,"productionId":1099538283976,"status":2,"updateTime":1610777071}],"productionStage":{"isReachEnd":0,"productionStageAwardStatus":0,"productionStageProgress":""},"speciality":{"factoryFlowerQualification":2,"factoryFlowerStatus":2,"skinQualification":2,"skinStatus":2},"systemVersion":"v1.3.1","user":{"createTime":1604029562,"currentLevel":3,"dataMark":0,"electric":1060338,"encryptPin":"khj_JOt3fCu2y7cz24EGrw==","headImage":"https://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83epzjs31icGQLtOyKdje7bRVicY5dibAU8DZdK4yCyrWh2I7NKn2nylCjkOUyPUvhUezEsmzPex9ibrTAg/132","isJXNewUser":0,"isProductSpecialCommodity":0,"mosaicPin":"18*9_p","nextLevelPercent":87,"nickname":"陈乐18276002037","npcStep":7,"pin":"18868699029_p","updateTime":1616642661,"userIdentity":"金牌学徒","xid":"1099535863712","zone":"dream_factory"},"userAttrExtInfo":{"electric":6000,"investElectricLimDays":0,"lastProduceInvestTime":0,"productLimFlag":0,"rewardType":3,"userType":2}},"msg":"OK","nowTime":1616659983,"ret":0}
            $farmInfo = json_decode($response);
            if($farmInfo->data->factoryList && $farmInfo->data->productionList){
                $production = $farmInfo->data->productionList[0];
                $output->writeln("京喜工厂状态：({$user->pt_pin} {$user->mobile}): {$production->investedElectric}/{$production->needElectric}");
                if ($production->investedElectric >= $production->needElectric) {
                    if(!$user->got_dream_factory) {
                        $user->got_dream_factory=1;
                        $user->save();
                        $this->notifyGotFruit($user);
                    }
                    $output->writeln("已经获得京喜工厂：{$user->pt_pin} {$user->mobile} {$user->remark}");
                } else {
                    if($user->got_dream_factory) {
                        $user->got_dream_factory=0;
                        $user->save();
                    }
                }
            } else {
                $output->writeln("京喜工厂活动未开始：({$user->pt_pin} {$user->mobile})");
                if($user->got_dream_factory) {
                    $user->got_dream_factory=0;
                    $user->save();
                }
            }
           
            
        } catch (\Throwable $th) {
            //throw $th;
            $output->writeln("获取用京喜工厂出错：{$user->id} {$user->pt_pin} {$th}");
            if($response){
                $output->writeln($response);
            }
            
        }
       
    }
    
    public function notifyGotFruit(JdUser $user){
        try {
            $config = config('wechat');
            $sendResult = $this->app->template_message->send([
                'touser' => $user->openid,
                'template_id' => $config['template_ids']['got_dream_factory'],
                'url' => "https://t.0xaa.cn/index/data?id={$user->id}",
                 'data' => [
                    'Account' => "{$user->pt_pin} ({$user->nickname} {$user->mobile} {$user->remark})"
                ]
            ]);
            echo json_encode($sendResult)."\n";
            return $sendResult;
        } catch (\Throwable $th) {
            throw $th;
            return false;
        }
    }

    function curl_post($url , $data=array(), $cookie,  $headers, $enableGzip = true){

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        // POST数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        //至关重要，CURLINFO_HEADER_OUT选项可以拿到请求头信息
        curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
       
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15); //timeout in seconds
        if($enableGzip) {
            curl_setopt($ch,CURLOPT_ENCODING , "gzip");
        }
        
        $output = curl_exec($ch);
        //通过curl_getinfo()可以得到请求头的信息
        // $responseHeader=curl_getinfo($ch);
        // echo json_encode($responseHeader);
        curl_close($ch);
        return $output;

    }

    function curl_get($url , $cookie,  $headers, $enableGzip = true){

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        //至关重要，CURLINFO_HEADER_OUT选项可以拿到请求头信息
        curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
       
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15); //timeout in seconds
        if($enableGzip) {
            curl_setopt($ch,CURLOPT_ENCODING , "gzip");
        }
        
        $output = curl_exec($ch);
        //通过curl_getinfo()可以得到请求头的信息
        // $responseHeader=curl_getinfo($ch);
        // echo json_encode($responseHeader);
        curl_close($ch);
        return $output;

    }
}
